import pickerView from '../../../../common/view/pickerview/pickerView';
import location from '../../../../common/code/pickerList/location.js';
import terminalModel from '../../../../common/code/pickerList/terminalModel.js';
const regexUtils = require('../../../../utils/RegexUtils.js');
import * as cacheUtils from '../../../../model/CacheUtils';
const constants = require('../../../../common/Constants.js');
const posUtil = require('../commonPos.js');
const UmfDialog = require('../../../../utils/UmfDialog.js');
import { $Toptips } from '../../../../components/CompRouter';
import network_utils from '../../../../http/NetworkUtils'
import PickerUtils from '../../../../model/PickerUtils';
// const umfToast = require('../../../../utils/UmfToast.js');
let cacheManager = null;
const PARAM_SIZE = 2;
let storeId = null;
var app = getApp()
Page(Object.assign({
  data: {
    //终端机具总数
    // totalModelItems: 1,
    terminalObjArray: [],
    cacheStorageData: {},
    installList:[]
  },

  onLoad: function (options) {
    
    // this.setData({
    //   cacheStorageData: options.terminalInfoData != "undefined" ? JSON.parse(options.terminalInfoData):""
    // })
    
    
    //获取缓存
    storeId = options.storeId;   
    cacheManager = new cacheUtils.cacheManager()
      .init("terminalPOSInfo" + storeId, constants.STORAGE_FUNC.TERMINALPOSINFO);
    let cacheStorage = cacheManager.getFunc();
    if (cacheStorage) {
      if (cacheStorage.installList) { 
       let installList = cacheStorage.installList
        this.setData({
          installList: installList,
          installArea: PickerUtils.getNormalHZByCode(installList, cacheStorage.installArea).toString(),
        })
        this.initNormalPicker([installList, terminalModel, terminalModel])
      } else {
        _requireInstallArea(this)
      }
      this.setData({
        cacheStorageData: cacheStorage,
        terminalObjArray: cacheStorage.terminalItem ? cacheStorage.terminalItem : [],       
      });      
    } else _requireInstallArea(this)
    // if (this.data.cacheStorageData) {
    //   _requireInstallArea(this)
    //   this.formateNetData(cacheStorageData)
    // }
    //终端机具空处理
    let terminalArray = convertEmptyModel(this.data.terminalObjArray);
    if (terminalArray.length == 0) {
      this.setData({
        terminalObjArray: [{ "modelNames": "", "terminalNums": "" ,"serialArr":[]}],
      });

    }
    //测试用TODO删除
    // this.initNormalPicker([terminalModel, terminalModel, terminalModel])
    
  },
  inputEvent: function (e) {
    let paramsKey = e.currentTarget.id;
    this._pageCacheStorage({ [paramsKey]: e.detail.value });
  },

  //处理网络请求回的数据
  // formateNetData:function(data){
  //   let modelNamesArr = data["modelNames"].split("-")
  //   let terminalNumsArr = data["terminalNums"].split("-")
  //   let snNumberArr = data["snNumber"].split("-")
  //   let terminalObjArray = []
  //   for (let i=0;i<modelNamesArr.length;i++){
  //     let serialArr = []
  //     let itemArr = snNumberArr[i].split(",")
  //     for (let j = 0; j < itemArr.length; j++) {
  //       let snListItem = {
  //         key: i,
  //         value: list[i].snNumber,
  //         checked: checked
  //       }
  //       serialArr.push(snListItem)
  //     }
  //     terminalObjArray.push({ "modelNames": modelNamesArr[i], "terminalNums": terminalNumsArr[i], "serialArr": serialArr })
  //   }
    
  //   this.setData({
  //     terminalObjArray: terminalObjArray,
  //     installArea: PickerUtils.getNormalHZByCode(installList, data.installArea).toString(),
  //   })
  //   cacheManager.cacheFunc({ "installArea": data.installArea, "getTermAmt": data.getTermAmt, "terminalItem": terminalObjArray})
  // },
  //点击导入序列号
  gotoSerial:function(e){
    let itemKey = e.currentTarget.id;
    let itemIndex = e.currentTarget.dataset.current;
    let terminalNum = this.data.terminalObjArray[itemIndex].terminalNums
    let modelNames = this.data.terminalObjArray[itemIndex].modelNames
    if (! modelNames){
      UmfDialog.show("请先选择终端型号")
      return
    } else if (!terminalNum){
      UmfDialog.show("请先填写机具数量")
      return
    }
    wx.navigateTo({
      url: './importSerialNo/importSerialNo?storeId=' + storeId + '&toolsNum=' + terminalNum + '&itemIndex=' + itemIndex + '&modelNames=' + modelNames,
    })
  },

  onNConfirmCB: function (idx, ret, code) {
    if (idx==0){
      //装机区域
      //TODO
      this.setData({
        installArea:ret
      })
      this._pageCacheStorage({ "installArea": PickerUtils.getNormalCodeByHZ(this.data.installList, ret).toString() });
    }else{
      //终端型号
      if (convertModelName(this.data.terminalObjArray, ret,idx-1)) {
        UmfDialog.show("终端型号不能重复添加")
        this.setData({
          errorMsg: "终端型号不能重复添加"
        });
      } else {
        let terminalObjArray = this.data.terminalObjArray
        terminalObjArray[idx - 1].serialArr=[]
        this.setData({
          errorMsg: "",
          terminalObjArray: terminalObjArray
        });
        this._pageCacheStorage({ "terminalItem": terminalObjArray });
        this._addTerminalModel({ "id": "modelNames", "current": idx-1, "value": ret });
      }
    }  
  },

  terminalinputEvent: function (e) {
    let itemKey = e.currentTarget.id;
    let itemIndex = e.currentTarget.dataset.current;
    if (itemKey == "terminalNums") {
      let snNum = this.data.terminalObjArray[itemIndex].serialArr ? this.data.terminalObjArray[itemIndex].serialArr.length:0
      if (e.detail.value < snNum) {
        UmfDialog.show("您当前选中了" + snNum + "个序列号，机具数量必须大于等于" + snNum)
        this.setData({
          terminalObjArray: this.data.terminalObjArray
        })
        return
      }
    }
    this._addTerminalModel({ "id": itemKey, "current": itemIndex, "value": e.detail.value });
  },



  loadMore: function (e) {
    this._addTerminalModel({ "id": "modelNames", "current": this.data.terminalObjArray.length + 1, "value": "" });
  },

  //提交按钮
  InfoSubmit: function (e) {
    let formData = e.detail.value;
    let errorMsg = this._checkForm(formData);
    posUtil.pageSubmit($Toptips, errorMsg);
  },

  /**
   * 点击删除按钮事件
   */
  delItem: function (e) {
    //获取列表中要删除项的下标
    // terminalModelArr.splice(terminalModelArr.length-1,1)
    let index = e.currentTarget.dataset.current;
    let terminalArray = this.data.terminalObjArray;
    if (terminalArray && terminalArray.length > index) {
      terminalArray.splice(index, 1);
    }

    this.setData({
      terminalObjArray: terminalArray,
      totalModelItems: this.data.totalModelItems - 1
    });
    //缓存数组
    this._pageCacheStorage({ "terminalItem": terminalArray });
  },



  /**
 * 添加机具（为防止缓存展示数据为空）
 * 
 * 判断当前添加数据的index是否存在terminalArray中
 * 1.存在  找到数组中index对应的对象赋值
 * 2.不存在 赋值
 */

  _addTerminalModel: function (e) {
    let itemKey = e.id;
    let itemIndex = e.current;
    //所有机具对象数组
    let terminalArray = this.data.terminalObjArray;
    if (terminalArray.length > itemIndex) {
      //数组存在itemIndex对象
      let itemObj = terminalArray[itemIndex];
      itemObj[itemKey] = e.value;
      terminalArray[itemIndex] = itemObj;
    } else {
      terminalArray.push(
        {
          [itemKey]: e.value
        }
      )
    }
    this.setData({
      terminalObjArray: terminalArray,
    });
    //终端机具空处理
    let terminalArray1 = convertEmptyModel(this.data.terminalObjArray);
    //缓存数组
    this._pageCacheStorage({ "terminalItem": terminalArray1 });
  },


  /**
 * 缓存统一处理
 * @param params
 * @param flag
 */
  _pageCacheStorage(params) {
    posUtil.cacheStorage({ "cacheManager": cacheManager, "params": params, "page": this, "pageName": "terminalPOSInfo", "minLength": PARAM_SIZE }, storeId);
  },

  _checkForm: function (data) {
    let formValues = data;
    //判断
    let resultErrorMsg = null;
    resultErrorMsg = regexUtils.regexTypeWithMsg(formValues["getTermAmt"], constants.RegexTypes.GETTERMAMT);
    if (resultErrorMsg) {
      return resultErrorMsg;
    }

    //item 校验
    let terminalArray = convertEmptyModel(this.data.terminalObjArray);
    if (terminalArray.length > 0) {
      for (let i = 0; i < terminalArray.length; i++) {
        let item = terminalArray[i];
        resultErrorMsg = regexUtils.regexTypeWithMsg(item["terminalNums"], constants.RegexTypes.TERMINALNUM)
        if (!item["modelNames"]) {
          return "请选择终端型号";
        }
        if (!item["terminalNums"]) {
          return "请添加机具数量";
        } else if (resultErrorMsg){
          return resultErrorMsg
          }else if (item["serialArr"] ? item["serialArr"].length < item["terminalNums"]:true){
          let num = i+1
          let msg = "请在第"+num+"组终端机具中选择" + item["terminalNums"]+"个序列号"
          return msg;
        }
      }
    } else {
      return "请添加终端机具";
    }
    return this.data.errorMsg;
  }


}, pickerView));

/**
 * 提取机具模型里不为空的数据
 */
function convertEmptyModel(modelArray) {
  let helpers = {
    filterModel: (item) => {
      return item["modelNames"] || item["terminalNums"] || item["serialArr"];
    },
  };
  return modelArray.filter(helpers.filterModel);
}

/**
 * 提取机具模型是否重复
 */
function convertModelName(modelArray, modelName,curr) {
  for (let i = 0; i < modelArray.length; i++) {
    if(i!=curr){
      if (modelArray[i]["modelNames"] == modelName) {
        return true;
      }
    }    
  }
  return false;
}

/**
 * 请求装机区域数据
 * params:page
 */
function _requireInstallArea(page){
  
  network_utils.buildRequest(constants.Interfaces.FUNC_GETINSTALLAREA, {}, {
    doHttpSucess: (response) => {
      if (constants.RetCodes.SUCCESS === response.retCode) {
        let list = response.list
        let areaList = []
        if (list.length>0){
          for (let i = 0;i<list.length;i++){
            let areaItem = {
              "label": list[i].areaName,
              "code": list[i].areaId
            }      
            areaList.push(areaItem)
          }
        }    
        else{
          UmfDialog.show("获取装机区域失败，请联系上级代理商")
        }    
       let installList = {
          "first": areaList
        }
        page.setData({
          installList:installList
        })   
        page._pageCacheStorage({ installList: installList}); 
        page.initNormalPicker([installList, terminalModel, terminalModel])
        return true;
      }
      return false;
    },
    doHttpFailure: function (erroData) {
      UmfDialog.show("获取装机区域失败，请检查网络")
    }
  }).send();
}
